<template>
  <div class="my-header flex justify-between items-center pl-3 pr-3">
    <div class="flex items-center">
      <p class="flex items-center w-44">
        <img src="/public/logo2.png" alt="" />
        <span class="text-base text-white font-bold ml-3">SCADA管理系统</span>
      </p>
      <!-- 折叠按钮 -->
      <p class="mt-2 ml-3">
        <el-icon :size="20" color="#fff" class="cursor-pointer" @click="toggleCollapse"
          ><Fold
        /></el-icon>
      </p>
      <!-- 面包屑 -->
      <p class="ml-4" v-if="breadInfo.groupName">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item class="font-bold cursor-pointer">{{
            breadInfo.groupName
          }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ breadInfo.jobName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </p>
    </div>
    <!-- 登录信息 -->
    <p>
      <!-- <el-button link size="large" class="btn-exit">
        Admin<el-icon size="large" color="#fff" class="el-icon--right"><SwitchButton /></el-icon>
      </el-button> -->
      <el-dropdown>
        <span class="el-dropdown-link flex items-center text-base">
          <el-icon color="#fff" size="large" class="el-icon--right mr-1"><User /></el-icon>
          <em class="not-italic text-white">Admin</em>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item disabled
              ><el-icon size="large" class="el-icon--right"><Key /></el-icon
              >修改密码</el-dropdown-item
            >
            <el-dropdown-item @click="loginOut"
              ><el-icon size="large" class="el-icon--right"><SwitchButton /></el-icon
              >退出系统</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </p>
  </div>
  <div class="my-container">
    <el-scrollbar>
      <!-- 菜单项 -->
      <el-menu
        :default-active="activeTab"
        class="el-menu-vertical-demo"
        :collapse="isCollapse"
        active-text-color="#409eff"
        background-color="#2d2e42"
        text-color="#fff"
        unique-opened
      >
        <template v-for="menuItem in menuList" :key="menuItem.name">
          <!-- 一级菜单 -->
          <el-sub-menu
            v-if="menuItem.children && menuItem.children.length > 0"
            :index="menuItem.name"
          >
            <template #title>
              <el-icon><component :is="menuItem.icon"></component></el-icon>
              <span>{{ menuItem.label }}</span>
            </template>
            <!-- 二级菜单 -->
            <template v-for="subMenuItem in menuItem.children" :key="subMenuItem.name">
              <el-menu-item :index="subMenuItem.name" @click="openTab(subMenuItem)">
                {{ subMenuItem.label }}
              </el-menu-item>
            </template>
          </el-sub-menu>
          <!-- 没有子菜单的一级菜单 -->
          <el-menu-item v-else :index="menuItem.name" @click="openTab(menuItem)">
            <template #default>
              <el-icon><component :is="menuItem.icon"></component></el-icon>
              <span>{{ menuItem.label }}</span>
            </template>
          </el-menu-item>
        </template>
        <!-- <el-menu-item
          v-for="menuItem in menuList"
          :key="menuItem.value"
          :index="menuItem.value"
          @click="openTab(menuItem)"
        >
          <template #title>
            <el-icon><component :is="menuItem.icon"></component></el-icon>
            <span>{{ menuItem.label }}</span>
          </template>
        </el-menu-item> -->
      </el-menu>
    </el-scrollbar>
    <el-scrollbar>
      <div class="my-content">
        <!-- Tab 页 -->
        <el-tabs
          v-if="activeTab"
          v-model="activeTab"
          type="card"
          closable
          @tab-remove="removeTab"
          @tab-click="clickTab"
        >
          <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name">
            <keep-alive :include="cachedComponents">
              <component :is="tab.component" :data="tab"></component>
            </keep-alive>
          </el-tab-pane>
        </el-tabs>
        <div v-else class="welcome">欢迎进入SCADA数据采集与监控系统</div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { markRaw, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Fold } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

import ComponentA from '../../template/page/templateA/Index.vue'
import ComponentB from '../../template/page/templateB/Index.vue'
import ComponentC from '../../template/page/templateC/Index.vue'
import ComponentD from '../../template/page/templateD/Index.vue'
import { useMessage } from '@/hooks/useMessage'
import { Query } from '@/api'
import { objectToQueryParams } from '@/utils/objectToQuery'

const comObj = reactive({
  A: markRaw(ComponentA),
  B: markRaw(ComponentB),
  C: markRaw(ComponentC),
  D: markRaw(ComponentD)
})

const message = useMessage()

const menuList = ref<any[]>([])
const getMenuList = async () => {
  const post = {
    groupName: 'SysMgt',
    jobType: 'SysInfo',
    operType: 'GetMenuInfo'
  }
  const inputStr = objectToQueryParams(post)
  const res = (await Query({ inputStr })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { groupName } = res.data.menuInfo
  //将数据转换为所需格式
  groupName.map((item: any) => {
    let children: any = []
    item.jobType.map((sub: any) => {
      children.push({
        ...sub,
        name: sub.value,
        groupName: item.value,
        jobType: sub.value,
        component: comObj[sub.template]
      })
    })
    menuList.value.push({
      id: item.id,
      label: item.label,
      name: item.value,
      icon: item.icon,
      children
    })
  })
}

// 当前打开的 Tab 页数组
const tabs = ref<any[]>([])

// 当前激活的 Tab 页
const activeTab = ref('')
// 已打开的Tab页
const cachedComponents = ref<string[]>([])

// 从本地存储中恢复 Tab 状态
const restoreTabs = () => {
  const storedActiveTab = sessionStorage.getItem('SCADA_ACTIVE_TAB')
  if (storedActiveTab) {
    activeTab.value = storedActiveTab
    // 查找匹配的父元素
    const menuParent = menuList.value.filter((parent) =>
      parent.children.some((child: any) => child.name === storedActiveTab)
    )
    // 匹配对应的子元素
    const menuItem = menuParent[0].children.find((item: any) => item.name === storedActiveTab)
    const { name, label } = menuItem
    setBreadInfo(name, label)
    tabs.value.push(menuItem)
  }
}

// 将 Tab 状态保存到本地存储
const saveTabs = () => {
  sessionStorage.setItem('SCADA_ACTIVE_TAB', activeTab.value)
}

// 打开 Tab 页
const openTab = (menuItem: any) => {
  setBreadInfo(menuItem.name, menuItem.label)

  const tabExists = tabs.value.some((tab: any) => tab.name === menuItem.name)
  if (!tabExists) {
    tabs.value.push(menuItem)
    cachedComponents.value.push(menuItem.component.name)
  }
  activeTab.value = menuItem.name
  saveTabs()
}

// 关闭 Tab 页
const removeTab = (index: string) => {
  const removedTab = tabs.value.find((tab) => tab.name === index)
  if (removedTab) {
    cachedComponents.value = cachedComponents.value.filter(
      (name) => name !== removedTab.component.name
    )
  }

  tabs.value = tabs.value.filter((tab) => tab.name !== index)
  if (activeTab.value === index) {
    activeTab.value = tabs.value.length > 0 ? tabs.value[tabs.value.length - 1].name : ''
    //设置面包屑数据
    if (activeTab.value) {
      setBreadInfo(tabs.value[tabs.value.length - 1].name, tabs.value[tabs.value.length - 1].label)
    } else {
      breadInfo.groupName = ''
      breadInfo.jobName = ''
    }
  }
  saveTabs()
}

// 选中 Tab 页
const clickTab = (tab: any) => {
  const { name, label } = tab.props
  activeTab.value = name
  setBreadInfo(name, label)
  saveTabs()
}

const setBreadInfo = (name: string, label: string) => {
  const tempArr = JSON.parse(JSON.stringify(menuList.value))
  // 查找匹配的父元素
  const match = tempArr.filter((parent: any) =>
    parent.children.some((child: any) => child.name === name)
  )
  breadInfo.groupName = match[0].label
  breadInfo.jobName = label
}

// 面包屑数据
const breadInfo = reactive({
  groupName: '',
  jobName: ''
})

const root = document.documentElement
//是否折叠菜单
const isCollapse = ref(false)
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  root.style.setProperty('--menu-width', isCollapse.value ? '63px' : '200px')
}

const { push } = useRouter()
//退出系统
const loginOut = () => {
  ElMessageBox.confirm('是否退出本系统？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      //调用退出接口
      localStorage.removeItem('SCADA_USER')
      message.success('退出成功')
      push({ path: '/login' })
    })
    .catch(() => {})
}

//用户登录信息
const user = ref('')

onMounted(async () => {
  await getMenuList()
  root.style.setProperty('--menu-width', '200px')
  user.value = localStorage.getItem('SCADA_USER') || ''
  restoreTabs()
})
</script>

<style scoped lang="less">
.my-container {
  display: flex;
  height: calc(100vh - 56px);
}
.el-menu {
  // width: 180px;
  height: calc(100vh - 56px);
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.my-content {
  width: calc(100vw - var(--menu-width));
  padding: 10px;
}
.my-header {
  background: #2d2e42;
  height: 56px;
  color: #fff;
}
.btn-exit {
  color: #fff;
  font-size: 16px;
}
.welcome {
  margin: 20px auto;
  width: 430px;
  height: 430px;
  background: url('@/assets/imgs/welcome3.jpg') no-repeat center bottom;
  background-size: 90%;
  font-size: 20px;
  color: #4256ce;
  letter-spacing: 5px;
  text-align: center;
  font-weight: 600;
}

.el-menu--collapse .el-sub-menu.is-active > .el-sub-menu__title i {
  // 默认折叠状态下二级菜单激活时一级菜单图标高亮
  color: var(--el-menu-active-color);
}

:deep(.el-breadcrumb__inner) {
  color: #fff !important;
}

:deep(.my-dropdown .el-dropdown-link) {
  color: #fff;
}
</style>
